package com.bwt.queue;

import java.util.Scanner;

public class ArrayQueueDemo {
	public static void main(String[] args) {

		//测试代码
		//创建一个队列
		ArrayQueue queue = new ArrayQueue(3);
		char key = ' ';	//接收用户输入
		Scanner scanner = new Scanner(System.in);
		boolean loop = true;
		//输出一个菜单
		while(loop){
			System.out.println("s(show):显示队列");
			System.out.println("e(exit):退出程序");
			System.out.println("a(add):添加数据到队列");
			System.out.println("g(get):从队列中取出数据");
			System.out.println("h(head):查看队列头的数据");
			key = scanner.next().charAt(0);	//接收一个字符
			switch(key){
				case 's':
					queue.show();
					break;
				case 'a':
					System.out.println("输出一个数");
					int value = scanner.nextInt();
					queue.addQueue(value);
					break;
				case 'h':	//查看队列头的数据
					try {
						int res = queue.headQueue();
						System.out.printf("队列头的数据是%d\n",res);
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
					break;
				case 'g':	//取出数据
					try {
						int res = queue.getQueue();
						System.out.printf("取出的数据是%d\n",res);
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
					break;
				case 'e':	//退出
					scanner.close();
					loop = false;
					break;
				default:
					break;
			}
		}
		System.out.println("程序退出-------");
	}

}

class ArrayQueue {
	//数组最大容量
	private int maxSize;

	//队列头
	private int front;

	//队列尾
	private int rear;

	//存储数组队列
	private int[] arr;

	public ArrayQueue(int maxSize) {
		this.maxSize = maxSize;
		arr = new int[maxSize];
		// 指向队列头部, front 指向队列头的前一个位置
		front = -1;
		// 指向队列尾部, 指向队列尾部的数组(即就是队列的最后一个数组)
		rear = -1;
	}

	public boolean isFull() {
		return rear == maxSize - 1;
	}

	public boolean isEmpty() {
		return front == rear;
	}

	public void addQueue(int n) {
		if (isFull()) {
			System.out.println("队列已满, 不能加入数据");
			return;
		}
		rear++;
		arr[rear] = n;
	}

	public int getQueue() {
		if (isEmpty()) {
			throw new RuntimeException("队列为空, 不能取数据");
		}
		front++;
		return arr[front];
	}

	public void show() {
		if (isEmpty()) {
			System.out.println("队列为空, 无法展示数组");
			return;
		}
		for (int i = 0; i < arr.length; i++) {
			System.out.printf("arr[%d]=%d\n", i, arr[i]);
		}
	}

	public int headQueue() {
		if (isEmpty()) {
			throw new RuntimeException("队列为空, 没有数据");
		}
		return arr[front + 1];
	}

}
